<template>
    <div style="border: 1px solid #ccc;">
      <!-- 工具栏 -->
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <!-- 编辑器 -->
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="content"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onChange="handleChange"
      />
    </div>
  </template>
  
  <script>
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  import { baseURL } from '@/utils/api'
  
  export default {
    name: 'RichTextEditor',
    components: { Editor, Toolbar },
    props: {
      value: {
        type: String,
        default: '',
      },
      preserveImages: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        editor: null,
        content: this.value,
        toolbarConfig: {
          excludeKeys: [
            'undo',      // 撤销
            'redo',      // 重做
            'uploadVideo',  // 上传视频
            'insertVideo'   // 插入视频
          ]
        },
        prevImageIds: null,
        uploadedImages: [], // 新增：用于存储上传的图片URL
        editorConfig: {
          placeholder: '请输入内容...',
          MENU_CONF: {
            uploadImage: {
              server: `${baseURL}/CodeQuestion-service/question/uploadFiles`,
              fieldName: 'file',
              maxFileSize: 10 * 1024 * 1024,
              allowedFileTypes: ['image/*'],
              meta: {
              },
              headers: {
              },
              customInsert: function(result, insertFn) {
                console.log(result)
                console.log(result.fileUrl)
                if (result.result === 'success') {
                  insertFn(result.fileUrl, '', {
                    style: {
                      width: '100px',
                      margin: '0 auto'
                    }
                  })
                } else {
                  console.error('图片上传失败:', result.message)
                }
              },
              onError: function(file, err, res) {
                console.error('图片上传出错:', err, res)
              },
              onProgress: function(progress) {
                console.log('上传进度:', progress)
              },
              onBeforeUpload: function(file) {
                if (file.size > 10 * 1024 * 1024) {
                  alert('图片大小不能超过 10MB')
                  return false
                }
                return true
              },
            },
            deleteImage: {
              customDestroy: async (src) => {
                console.log('customDestroy 被触发')
                console.log('要删除的图片 src:', src)
                try {
                  console.log('准备调用删除接口')
                  const response = await fetch(`${baseURL}/CodeQuestion-service/question/delete?fileUrl=${encodeURIComponent(src)}`, {
                    method: 'DELETE'
                  })
                  
                  const result = await response.json()
                  console.log('删除接口返回结果:', result)
                  if (result.result !== 'success') {
                    console.error('删除图片失败:', result.message)
                  } else {
                    console.log('图片删除成功')
                  }
                } catch (error) {
                  console.error('删除图片出错:', error)
                }
              }
            }
          },
          hoverbarKeys: {
            image: {
              menuKeys: [
                'deleteImage',
                'imageWidth30',
                'imageWidth50',
                'imageWidth100'
              ]
            }
          }
        },
        mode: 'default',
      }
    },
    created() {
      // 添加路由守卫
      this.$router.beforeEach((to, from, next) => {
        // 只有当不需要保留图片时才删除
        if (!this.preserveImages) {
          this.deleteAllImages()
        }
        next()
      })
    },
    mounted() {
      // 添加页面关闭事件监听
      window.addEventListener('beforeunload', this.handleBeforeUnload)
    },
    beforeDestroy() {
      // 清理事件监听
      window.removeEventListener('beforeunload', this.handleBeforeUnload)
      
      console.log('富文本编辑器销毁，preserveImages:', this.preserveImages)
      
      // 只有当不需要保留图片时才删除
      if (!this.preserveImages) {
        // 组件销毁时删除所有图片
        this.deleteAllImages()
      }
      
      if (this.editor) {
        this.editor.destroy()
        this.editor = null
      }
    },
    watch: {
      // 监听父组件传入的 value 值，更新编辑器内容
      value(newValue) {
        if (newValue !== this.content) {
          this.content = newValue;
        }
      },
      // 监听编辑器内容的变化，更新父组件的 value 值
      content(newContent) {
        this.$emit('input', newContent);
      },
    },
    methods: {
      // 新增：删除所有已上传的图片
      async deleteAllImages() {
        // 如果需要保留图片，则不执行删除
        if (this.preserveImages) {
          console.log('需要保留图片，跳过删除操作')
          return
        }
        
        const images = this.editor?.getElemsByType('image') || []
        const imageUrls = images.map(elem => elem.src)
        
        console.log('准备删除所有图片，数量:', imageUrls.length)
        
        for (const imageUrl of imageUrls) {
          try {
            const response = await fetch(`${baseURL}/CodeQuestion-service/question/delete?fileUrl=${encodeURIComponent(imageUrl)}`, {
              method: 'DELETE'
            })
            const result = await response.json()
            console.log('删除图片结果:', result)
          } catch (error) {
            console.error('删除图片失败:', error)
          }
        }
      },
      
      // 修改：页面关闭时的处理函数
      handleBeforeUnload(event) {
        // 如果需要保留图片，则不执行删除
        if (this.preserveImages) {
          console.log('需要保留图片，跳过删除操作')
          return
        }
        
        const images = this.editor?.getElemsByType('image') || []
        const imageUrls = images.map(elem => elem.src)
        
        if (imageUrls.length > 0) {
          // 使用同步 XMLHttpRequest 确保在页面关闭前删除图片
          imageUrls.forEach(imageUrl => {
            const xhr = new XMLHttpRequest()
            xhr.open('DELETE', `${baseURL}/CodeQuestion-service/question/delete?fileUrl=${encodeURIComponent(imageUrl)}`, false)
            xhr.send()
          })
        }
      },
      
      onCreated(editor) {
        this.editor = Object.seal(editor);
        
        // 添加删除图片的监听
        editor.on('delete', async (node) => {
          console.log('delete 事件被触发')
          console.log('删除的节点类型:', node.type)
          if (node.type === 'image') {
            console.log('检测到图片节点，准备删除')
            try {
              const imageUrl = node.src
              console.log('图片URL:', imageUrl)
              
              // 调用删除接口
              const response = await fetch(`${baseURL}/CodeQuestion-service/question/delete?fileUrl=${encodeURIComponent(imageUrl)}`, {
                method: 'DELETE'
              })
              
              const result = await response.json()
              console.log('删除接口返回结果:', result)
              if (result.result !== 'success') {
                console.error('删除图片失败:', result.message)
              }
            } catch (error) {
              console.error('删除图片出错:', error)
            }
          }
        })

        // 添加节点销毁监听
        editor.on('destroyed', (node) => {
          console.log('destroyed 事件被触发')
          console.log('被销毁的节点:', node)
        })
      },
      handleChange(editor) {
        // 监听内容变化，包括删除操作
        const elemIds = editor.getElemsByType('image').map(elem => elem.src)
        
        // 如果之前有图片，现在被删除了，就触发删除操作
        if (this.prevImageIds) {
          const deletedImages = this.prevImageIds.filter(id => !elemIds.includes(id))
          if (deletedImages.length > 0) {
            deletedImages.forEach(async (imageUrl) => {
              console.log('图片被删除:', imageUrl)
              try {
                const response = await fetch(`${baseURL}/CodeQuestion-service/question/delete?fileUrl=${encodeURIComponent(imageUrl)}`, {
                  method: 'DELETE'
                })
                
                const result = await response.json()
                console.log('删除接口返回结果:', result)
                if (result.result !== 'success') {
                  console.error('删除图片失败:', result.message)
                }
              } catch (error) {
                console.error('删除图片出错:', error)
              }
            })
          }
        }
        
        // 更新图片ID列表
        this.prevImageIds = elemIds
      },
      onInput() {
        this.$emit('input', this.content);
      },
      onFileChange(event) {
        const file = event.target.files[0];
        if (file) {
          this.$emit('upload-image', file);
        }
      },
      deleteImage(imageUrl) {
        this.$emit('delete-image', imageUrl);
      }
    },
  }
  </script>
  
  <style src="@wangeditor/editor/dist/css/style.css"></style>